import { ref } from "vue";
import { watch } from "vue";
import { useLayout } from "@/stores/layout";
import { BalanceHistory } from "./ChartConfig";
import { useCapital } from "@/stores/capital";
import { Bus, CLEVER_CHART_SWITCH, CLEVER_TYPE_SWITCH, CONN_ACTIVITY } from "@/connetion/Bus";
import { getFormatTime, formatBigNumber } from "@/comm/format";

/**按钮枚举 */
enum DownType {
    /**数据异动 */
    DataChanges,
    /**余额历史记录 */
    BalanceHistory
}
const lodding = ref(false);
/**nva按钮数据类型 */
interface BtnsType {
    label: string;
    value: string | null;
}

enum CTYPE {
    area = `<span class="iconfont icon-gupiao"></span>`,
    solid = `<span class="mdi mdi-chart-line"></span>`
    // solid = `<span class="iconfont icon-gupiao1"></span>`
}

/**时间nav按钮数据 */
const btnsData = [
    {
        label: "D",
        value: "D"
    },
    {
        label: "H",
        value: "H"
    },
    {
        label: CTYPE.solid,
        value: "line"
    }
];

class YTab {
    static list: any[] = [];
    static btns = ref<BtnsType[]>(btnsData);
    static idx = ref(YTab.btns.value[0]);
    static page = ref(DownType.DataChanges);
    static onTypeChange: (t: any) => void;
    static onnvadown: (val: number) => void;
    static resize: () => void;
    static initChat: () => void;
}

YTab.resize = () => {
    if (kfig) {
        kfig.figTab?.resize();
        setTimeout(() => {
            kfig?.figTab?.resize();
        }, 300);
    }
};
YTab.initChat = async () => {
    lodding.value = true;
    await capital.loadHistory();
    if (YTab.list && YTab.list.length) {
        console.log("addBalanceHistory 重置 ##############################");
        Kfig.addBalanceHistory(YTab.list);
    }
}

//6|10|15按钮切换
YTab.onTypeChange = function (t: any) {
    // console.log("yzt 按钮切换==========>", t);
    // YTab.idx.value
    // console.log(YTab.idx)
    Bus.emit(CLEVER_TYPE_SWITCH, t);
    if (t.value == "line") {
        // let label = YTab.btns.value[2].label;
        YTab.btns.value[2].label = t.label == CTYPE.area ? CTYPE.solid : CTYPE.area;
    }
};
//数据异动 and 余额历史记录 监听
YTab.onnvadown = async function (val: number) {
    YTab.page.value = val;
    switch (val) {
        case DownType.DataChanges:
            Bus.emit(CLEVER_CHART_SWITCH);
            break;
        case DownType.BalanceHistory:
            lodding.value = true;
            await capital.loadHistory();
            if (YTab.list && YTab.list.length) {
                Kfig.addBalanceHistory(YTab.list);
                // console.log("yzt__重置");
            }
            break;
    }
};


//---------以下是图表数据生成操作------
let kfig: Kfig | undefined;

//监听图表大小变化
watch(
    () => useLayout().newsOpen,
    () => {
        setTimeout(() => {
            kfig?.figTab?.resize();
        }, 200);
    }
);
const capital = useCapital();
//监听
watch(
    () => capital.detail,
    (newVal: any, oldVal: any) => {
        console.log("capital.blockBalanceList", capital.curblockBalance);
        // console.log('yzt', newVal);
        // if (YTab.page.value === DownType.BalanceHistory) {
        // console.log('yzt历史数据');
        // Kfig.addBalanceHistory(newVal.contractAddress);
        // }
        // curItem.value = newVal[0];
        // console.log('yzt下拉数据变化', newVal[0]);
    }
);

watch(
    () => capital.historyAmount,
    (newVal: any, oldVal: any) => {
        lodding.value = false;
        console.log("获取到历史数据#################", newVal);
        Kfig.addBalanceHistory(newVal);
    }
);

interface DayData {
    timestamp: number;
    balance: number;
}
class Kfig {
    static addBalance: { name: string; token: string } | undefined;
    figTab: echarts.ECharts | undefined;
    //初始化数据表div元素对象
    constructor(element: HTMLDivElement | HTMLCanvasElement) {
        // this.figTab?.clear();
        this.figTab = echarts.init(element);
        setTimeout(() => {
            this.figTab?.resize();
        }, 100);
    }
    //设置图表数据
    private setFigTab(option: any) {
        // this.figTab?.clear()
        // console.log("this.figTab", this.figTab)
        this.figTab?.setOption(option);
        console.log('设置图表数据', option)
        return this;
    }
    /**生成数据异动图表数据 */
    static addDataChanges() {
        // kfig = new Kfig(document.getElementById('y_chart') as HTMLDivElement).setFigTab(DataChangesOption)
    }
    /**生成余额历史记录 */
    static addBalanceHistory(ary: DayData[]) {
        YTab.list = ary;

        //数据小到大排序
        // const newRes = res.data.tokenDayDatas.sort((a, b) => a.date - b.date);
        console.log("yzt历史表数据", JSON.parse(JSON.stringify(ary)));

        (BalanceHistory as any).xAxis.boundaryGap = false;
        (BalanceHistory as any).xAxis.data = ary.map(item => getFormatTime(item.timestamp, "MM-dd"));
        (BalanceHistory as any).series[0].data = ary.map(item => item.balance);
        // (BalanceHistory as any).series[0].markPoint = {
        //     data: [{
        //         type: "max", name: "max", symbol: 'circle', symbolSize: [40, 30]
        //     },
        //     { type: 'min', name: 'min', symbol: 'circle', symbolSize: [40, 30] }],
        // };
        // (BalanceHistory as any).series[0].data = ary.map(item => Kfig.balanceFormat(item.balance));
        (BalanceHistory as any).yAxis.max = (val: any) => {
            return val.max
        }
        (BalanceHistory as any).yAxis.min = (val: any) => {
            return val.min
        }
        (BalanceHistory as any).yAxis.axisLabel = {
            formatter: (value: any) => {
                return formatBigNumber(value)
            }
        };
        // console.log('yzt', BalanceHistory);

        console.log("初始化表格 y_chart");

        kfig = new Kfig(document.getElementById("y_chart") as HTMLDivElement).setFigTab(BalanceHistory);
        // kfig = new Kfig(document.getElementById('y_chart') as HTMLDivElement).setFigTab(ary);
        kfig!.setFigTab(BalanceHistory);

        // kfig!.figTab!.on("click", 'series.line', (e:any)=>{
        //     console.log(e, "---0")
        // })
    }
    static balanceFormat(val: any) {
        const absValue = Math.abs(val);
        if (absValue >= 1000000000) {
            return (absValue / 1000000000).toFixed(3)
        } else if (absValue >= 1000000) {
            return (absValue / 1000000).toFixed(3)
        } else if (absValue >= 1000) {
            return (absValue / 1000).toFixed(3)
        } else {
            return absValue.toFixed(3);
        }
    }
    static getUnits(val: any) {
        const absValue = Math.abs(val);
        if (absValue >= 1000000000) {
            return 'B'
        } else if (absValue >= 1000000) {
            return 'M'
        } else if (absValue >= 1000) {
            return 'K'
        } else {
            return ''
        }
    }
}


export { YTab, Kfig, DownType, kfig, lodding };
